// router/index.ts

import { createRouter, createWebHashHistory} from 'vue-router';
import type { RouteRecordRaw } from 'vue-router';
import home from '../components/home.vue';
import login from '../components/login.vue';
import play_views from '../items/video_items/play_views.vue';
import {ElMessage} from "element-plus";
import home_view from '../items/home_view.vue';
import account_setting from '../items/account_setting.vue';
import BarChart from '../items/home_items/BarChart.vue';

const routes: Array<RouteRecordRaw> = [
    {
        path: '/',
        name: 'home',
        component: home,
        props:true,
        meta: { requiresAuth: true } // 这个路由需要认证
    },
    {
        path: '/login',
        name: 'login',
        component: login,
        props:true,
    },
    {
        path: '/home_view',
        name: 'home_view',
        component: home_view,
        props:true,
    },
    {
        path: '/BarChart',
        name: 'BarChart',
        component: BarChart,
        props:true,
    },
    {
        path: '/account_setting',
        name: 'account_setting',
        component: account_setting,
        props:true,
    },
    {
        path: '/play_views',
        name: 'play_views',
        component: play_views,
        props:true,
    },

];

// const router = createRouter({
//     history: createWebHistory(process.env.BASE_URL),
//     routes
// });
const router = createRouter({
    history: createWebHashHistory(),
    routes
})

router.beforeEach((to, from, next) => {
    // 检查路由是否需要登录
    if (to.meta.requiresAuth) {
        // 如果用户未登录，则重定向到登录页面
        if (!localStorage.getItem('key')) {
            ElMessage({
                type: 'error',
                message: '请先登录',
            })
            next('/login');
        } else {
            // 如果用户已登录，则继续到请求的路由
            next();
        }
    } else {
        // 如果路由不需要登录，则正常继续
        next();
    }
})

export default router;
